const cartDao = require('../dao/cartDao');
const productDao = require('../dao/productDao');
const checkLogin = require('../middleware/checkLogin');

const utils = {
    /**
     * 组装购物车
     * @param {*} data 
     * @returns 
     */
    getShoppingCart: async data => {
        const shoppingCart = [];
        for (let i = 0, len = data.length; i < len; i++) {
            const temp = data[i];
            const product = await productDao.getProductDetailsById(temp.product_id);
            const shoppingMap = {
                id: temp.id,
                productID: temp.product_id,
                productName: product[0].product_name,
                productImg: product[0].product_picture,
                price: product[0].product_selling_price,
                num: temp.num,
                maxNum: Math.floor(product[0].product_num / 2),
                check: false
            }
            shoppingCart.push(shoppingMap)
        }
        return shoppingCart
    }
}

module.exports = {
    /**
     * 添加商品
     * @param {*} ctx 
     * @returns 
     */
    addShoppingCart: async ctx => {
        const { user_id, product_id } = ctx.request.body;
        // 校验用户是否登录
        if (!checkLogin(ctx, user_id)) {
            return;
        }
        // 1. 查询购物车中是否存在该商品
        const cart = await cartDao.findProduct(user_id, product_id);
        // 2. 如果存在该商品，则数量+1
        if (cart.length > 0) {
            const tempNum = cart[0].num + 1;
            const product = await productDao.getProductDetailsById(product_id);
            const maxNum = Math.floor(product[0].product_num / 2);
            // 4. 判断是否达到购买上限
            if (tempNum > maxNum) {
                ctx.body = {
                    status: 80200,
                    message: 'success',
                    data: {
                        code: '3',
                        msg: `购买数量达到上限 ${maxNum}`
                    }
                }
                return;
            }
            try {
                // 5.数量没有达到购买上限，更新记录
                const result = await cartDao.updateCart(tempNum, user_id, product_id);
                if (result.affectedRows === 1) {
                    ctx.body = {
                        status: 80200,
                        message: 'success',
                        data: {
                            code: '2',
                            msg: '购物车商品数量更新成功'
                        }
                    }
                }
            } catch (error) {
                Promise.reject(error);
            }
        } else {
            // 3.如果不存在，则添加进购物车
            try {
                const result = await cartDao.addCart(user_id, product_id);
                if (result.affectedRows === 1) {
                    // 6. 如果添加成功，获取该用户的购物车信息
                    const cart = await cartDao.getCart(user_id)
                    const data = await utils.getShoppingCart(cart)
                    ctx.body = {
                        status: 80200,
                        message: 'success',
                        data: {
                            code: '1',
                            msg: '添加购物车成功',
                            data
                        }
                    }
                    return;
                }
            } catch (error) {
                Promise.reject(error)
            }
        }
    },
    /**
     * 删除购物车中指定商品
     * @param {*} ctx 
     * @returns 
     */
    deleteShoppingCart: async ctx => {
        const { user_id, product_id } = ctx.request.query;
        // 校验用户是否登录
        if (!checkLogin(ctx, user_id)) {
            return;
        }
        // 1.判断购物车中是否存在该商品
        const cart = await cartDao.findProduct(user_id, product_id);
        if (cart.length) {
            try {
                // 2. 删除商品
                const result = await cartDao.deleteProduct(user_id, product_id);
                if (result.affectedRows === 1) {
                    ctx.body = {
                        status: 80200,
                        message: 'success',
                        data: {
                            code: '1',
                            msg: '删除商品成功'
                        }
                    }
                }
            } catch (error) {
                Promise.reject(error)
            }
        } else {
            ctx.body = {
                status: 80200,
                message: 'success',
                data: {
                    code: '2',
                    msg: '该商品不存在'
                }
            }
        }
    },
    /**
     * 更新购物车中商品数量
     * @param {*} ctx 
     * @returns 
     */
    updateShoppingCart: async ctx => {
        const { user_id, product_id, num } = ctx.request.body;
        // 校验用户是否登录
        if (!checkLogin(ctx, user_id)) {
            return;
        }
        if (num < 1) {
            ctx.body = {
                status: 80200,
                message: 'success',
                data: {
                    code: '4',
                    msg: '数量不合法'
                }
            }
            return
        }
        // 判断商品是否cunz
        const cart = await cartDao.findProduct(user_id, product_id);
        if (cart.length) {
            if (cart[0].num === num) {
                ctx.body = {
                    status: 80200,
                    message: 'success',
                    data: {
                        code: '3',
                        msg: '数量无增减'
                    }
                }
                return
            }
            const product = await productDao.getProductDetailsById(product_id);
            const maxNum = Math.floor(product[0].product_num / 2);
            // 4. 判断是否达到购买上限
            if (num > maxNum) {
                ctx.body = {
                    status: 80200,
                    message: 'success',
                    data: {
                        code: '4',
                        msg: `购买数量达到上限 ${maxNum}`
                    }
                }
                return;
            }
            try {
                const result = await cartDao.updateCart(num, user_id, product_id);
                console.log('result', result)
                if (result.affectedRows === 1) {
                    ctx.body = {
                        status: 80200,
                        message: 'success',
                        data: {
                            code: '1',
                            msg: '购物车商品数量更新成功'
                        }
                    }
                } else {
                    ctx.body = {
                        status: 80200,
                        message: 'success',
                        data: {
                            code: '0',
                            msg: '购物车商品数量更新失败'
                        }
                    }
                }
            } catch (error) {
                return Promise.reject(error)
            }
        } else {
            ctx.body = {
                status: 80200,
                message: 'success',
                data: {
                    code: '2',
                    msg: '该商品不存在'
                }
            }
        }
    }
}